<template>
  <div class="app-container p-6">
    <!-- 页面标题和操作按钮 - 完全匹配原型 -->
    <div class="page-header-section flex flex-col md:flex-row md:items-center md:justify-between mb-6">
      <div class="page-title-area">
        <h1 class="text-2xl font-bold text-text-primary">菜单管理</h1>
        <p class="text-text-muted mt-2">管理系统中的菜单结构，包括目录、菜单和按钮权限的配置</p>
      </div>
      <div class="page-actions-area mt-4 md:mt-0 flex items-center gap-2">
        <!-- 展开/折叠按钮 -->
        <button
          @click="toggleExpandAll"
          class="secondary-action-btn px-4 py-2 border border-border rounded-md text-text-secondary hover:bg-bg-hover hover:text-text-primary transition-colors flex items-center"
        >
          <i :class="isExpandAll ? 'fas fa-compress-arrows-alt' : 'fas fa-expand-arrows-alt'" class="mr-2"></i>
          <span>{{ isExpandAll ? '全部折叠' : '全部展开' }}</span>
        </button>
        
        <!-- 主要操作按钮 -->
        <button
          @click="handleAdd"
          v-permission="'menu:create'"
          class="primary-action-btn bg-primary hover:bg-primary-hover text-white px-6 py-2 rounded-md flex items-center shadow-card transition-all"
        >
          <i class="fas fa-plus mr-2"></i>
          <span>新增菜单</span>
        </button>
      </div>
    </div>

    <!-- 搜索和筛选区域 - 完全匹配原型样式 -->
    <div class="search-form-card bg-panel rounded-lg shadow-card p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <!-- 菜单名称搜索 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">菜单名称</label>
          <div class="relative">
            <input
              type="text"
              v-model="queryParams.menuName"
              @keyup.enter="handleQuery"
              placeholder="请输入菜单名称"
              class="search-input pl-10 pr-4 py-2 w-full rounded-md border border-border bg-bg-hover focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            >
            <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-muted"></i>
          </div>
        </div>

        <!-- 菜单类型筛选 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">菜单类型</label>
          <div class="search-select-wrapper">
            <el-select
              v-model="queryParams.menuType"
              placeholder="全部类型"
              clearable
              class="search-select w-full"
            >
              <el-option label="目录" value="DIR" />
              <el-option label="菜单" value="MENU" />
              <el-option label="按钮" value="BUTTON" />
            </el-select>
          </div>
        </div>

        <!-- 状态筛选 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">状态</label>
          <div class="search-select-wrapper">
            <el-select
              v-model="queryParams.status"
              placeholder="全部状态"
              clearable
              class="search-select w-full"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </div>
        </div>
      </div>

      <!-- 高级搜索和操作按钮 -->
      <div class="mt-4 flex justify-between items-center">
        <button class="text-primary hover:text-primary-hover text-sm transition-colors">
          <i class="fas fa-sliders-h mr-1"></i>
          高级搜索
        </button>

        <!-- 操作按钮组 -->
        <div class="flex space-x-3">
          <button
            @click="resetQuery"
            class="px-4 py-2 border border-border rounded-md text-text-secondary hover:bg-bg-hover transition-colors"
          >
            重置
          </button>
          <button
            @click="handleQuery"
            class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-hover shadow-sm transition-colors"
          >
            搜索
          </button>
        </div>
      </div>
    </div>

    <!-- 菜单树形表格 -->
    <div class="system-table-wrapper">
      <!-- 表格头部区域 -->
      <div class="table-header bg-bg-hover border-b border-border flex justify-between items-center p-4">
        <div class="table-title text-text-secondary font-medium">菜单列表</div>
        <div class="table-actions flex items-center space-x-2">
          <button class="header-action-btn" title="刷新" @click="getList">
            <i class="fas fa-sync-alt"></i>
          </button>
        </div>
      </div>

      <!-- 表格内容 -->
      <div class="system-table">
        <el-table
          v-loading="loading"
          :data="filteredMenuList"
          row-key="id"
          :default-expand-all="isExpandAll"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          style="width: 100%"
        >
          <el-table-column label="菜单名称" min-width="200">
            <template #default="{ row }">
              <span class="d-inline-flex items-center">
                <el-icon v-if="getIconComponent(row.icon)" class="mr-2">
                  <component :is="getIconComponent(row.icon)" />
                </el-icon>
                {{ row.title || row.name }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="路由地址" min-width="150">
            <template #default="{ row }">{{ row.path }}</template>
          </el-table-column>
          <el-table-column label="菜单类型" width="100" align="center">
            <template #default="{ row }">
              <span
                class="status-tag"
                :class="{
                  'status-enabled': row.menuType === 'DIR',
                  'status-pending': row.menuType === 'MENU',
                  'status-disabled': row.menuType === 'BUTTON'
                }"
              >
                {{ getMenuTypeText(row.menuType) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="组件路径" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">{{ row.component }}</template>
          </el-table-column>
          <el-table-column label="权限标识" min-width="120">
            <template #default="{ row }">{{ row.permission }}</template>
          </el-table-column>
          <el-table-column prop="orderNo" label="排序" width="80" align="center" />
          <el-table-column label="可见" width="60" align="center">
            <template #default="{ row }">
              <span
                class="status-tag"
                :class="(row.visible === true) ? 'status-enabled' : 'status-disabled'"
              >
                {{ (row.visible === true) ? '是' : '否' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }">
              <span
                class="status-tag"
                :class="(row.status === 1) ? 'status-enabled' : 'status-disabled'"
              >
                {{ (row.status === 1) ? '启用' : '禁用' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="160">
            <template #default="{ row }">{{ row.createTime }}</template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="120">
            <template #default="{ row }">
              <div class="table-actions">
                <button
                  class="action-btn view-btn"
                  @click="handleAddChild(row)"
                  v-permission="'menu:create'"
                  title="添加子菜单"
                >
                  <i class="fas fa-plus"></i>
                </button>
                <button
                  class="action-btn edit-btn"
                  @click="handleEdit(row)"
                  v-permission="'menu:update'"
                  title="编辑"
                >
                  <i class="fas fa-edit"></i>
                </button>
                <button
                  class="action-btn delete-btn"
                  @click="handleDelete(row)"
                  v-permission="'menu:delete'"
                  title="删除"
                >
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>

  <!-- 新增/编辑菜单对话框 -->
  <el-dialog
    v-model="formVisible"
    :title="isEdit ? '编辑菜单' : '新增菜单'"
    width="680px"
    destroy-on-close
  >
    <el-form
      ref="menuFormRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="上级菜单" prop="parentId">
            <el-tree-select
              v-model="formData.parentId"
              :data="parentMenuOptions"
              node-key="id"
              :props="{ label: 'title', value: 'id', children: 'children' }"
              placeholder="请选择上级菜单（留空则为顶级菜单）"
              clearable
              filterable
              check-strictly
              :render-after-expand="false"
              default-expand-all
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="菜单类型" prop="menuType">
            <el-radio-group v-model="formData.menuType">
              <el-radio label="DIR">目录</el-radio>
              <el-radio label="MENU">菜单</el-radio>
              <el-radio label="BUTTON">按钮</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="菜单图标" prop="icon">
            <IconPicker v-model="formData.icon" placeholder="请选择菜单图标" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="菜单名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入菜单名称（标识符）"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="菜单标题" prop="title">
            <el-input
              v-model="formData.title"
              placeholder="请输入菜单标题（显示名）"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="路由地址" prop="path">
            <el-input
              v-model="formData.path"
              placeholder="请输入路由地址"
              :disabled="formData.menuType === 'BUTTON'"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="组件路径" prop="component">
            <el-input
              v-model="formData.component"
              placeholder="请输入组件路径"
              :disabled="formData.menuType !== 'MENU'"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="权限标识" prop="permission">
            <el-input
              v-model="formData.permission"
              placeholder="请输入权限标识"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="排序号" prop="orderNo">
            <el-input-number
              v-model="formData.orderNo"
              :min="0"
              :max="9999"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="是否可见" prop="visible">
            <el-radio-group v-model="formData.visible">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="菜单状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="formData.menuType !== 'BUTTON'">
          <el-form-item label="是否外链" prop="isFrame">
            <el-radio-group v-model="formData.isFrame">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="formData.menuType === 'MENU'">
          <el-form-item label="是否缓存" prop="isCache">
            <el-radio-group v-model="formData.isCache">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElSelect, ElOption, ElRow, ElCol, ElInputNumber } from 'element-plus'
import * as ElementPlusIcons from '@element-plus/icons-vue'
import { menuApi } from '@/api/menu'
import type { MenuDTO } from '@/types/api'
import IconPicker from '@/components/IconPicker/index.vue'

// 响应式数据
const loading = ref(false)
const menuList = ref<MenuDTO[]>([])
const isExpandAll = ref(false)

// 表单相关
const formVisible = ref(false)
const isEdit = ref(false)
const menuFormRef = ref<any>()

// 表单数据 - 直接使用后端字段名
const formData = reactive<{
  id?: string
  name: string
  title: string
  parentId: string | null
  path: string
  component: string
  icon: string
  menuType: string
  permission: string
  orderNo: number
  status: number
  visible: boolean
  isFrame: boolean
  isCache: boolean
}>({
  id: undefined,
  name: '',
  title: '',
  parentId: null,
  path: '',
  component: '',
  icon: '',
  menuType: 'MENU',
  permission: '',
  orderNo: 0,
  status: 1,
  visible: true,
  isFrame: false,
  isCache: true
})

// 查询表单参数（用户输入）
const queryParams = reactive({
  menuName: '',
  menuType: '',
  status: undefined as number | undefined
})

// 实际应用的查询条件（点击搜索后才更新）
const appliedQuery = reactive({
  menuName: '',
  menuType: '',
  status: undefined as number | undefined
})

// 表单验证规则 - 使用后端字段名
const formRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '菜单名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入菜单标题', trigger: 'blur' },
    { min: 2, max: 50, message: '菜单标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  menuType: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ],
  path: [
    { required: false, message: '请输入路由地址', trigger: 'blur' }
  ],
  orderNo: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 计算属性 - 父菜单选项（用于树形选择）- 直接使用后端字段
const parentMenuOptions = computed(() => {
  // 检查某个菜单是否是当前编辑菜单的子菜单
  const isChildOfCurrent = (id: string, currentId: string, menus: MenuDTO[]): boolean => {
    for (const menu of menus) {
      if ((menu as any).id === currentId) {
        // 找到当前菜单，检查是否包含 id
        return checkInChildren(id, menu)
      }
      // 递归检查子菜单
      const children = menu.children || []
      if (children.length > 0 && isChildOfCurrent(id, currentId, children)) {
        return true
      }
    }
    return false
  }
  
  // 检查某个菜单ID是否在子菜单中
  const checkInChildren = (id: string, parentMenu: MenuDTO): boolean => {
    const children = parentMenu.children || []
    for (const child of children) {
      if ((child as any).id === id) {
        return true
      }
      if (checkInChildren(id, child)) {
        return true
      }
    }
    return false
  }
  
  const processMenuTree = (menus: MenuDTO[]): any[] => {
    return menus
      .filter(menu => {
        // 编辑时过滤掉自己和自己的子菜单
        if (isEdit.value && formData.id) {
          const currentId = formData.id
          // 不能选择自己
          if ((menu as any).id === currentId) {
            return false
          }
          // 不能选择自己的子菜单
          if (isChildOfCurrent((menu as any).id!, currentId, menuList.value)) {
            return false
          }
        }
        return true
      })
      .map(menu => ({
        id: (menu as any).id,
        title: menu.title || (menu as any).name,
        menuType: menu.menuType,
        children: menu.children ? processMenuTree(menu.children) : []
      }))
  }
  
  // 添加顶级菜单选项
  const options = processMenuTree(menuList.value)
  return [
    {
      id: null,
      title: '顶级菜单',
      menuType: 'DIR',
      children: []
    },
    ...options
  ]
})

// 计算属性 - 过滤后的菜单列表 - 使用实际应用的查询条件
const filteredMenuList = computed(() => {
  const filterMenu = (menus: MenuDTO[]): MenuDTO[] => {
    return menus.filter(menu => {
      // 菜单名称筛选 - 使用后端的 title 字段
      const nameMatch = !appliedQuery.menuName || 
        (menu.title || (menu as any).name || '').toLowerCase().includes(appliedQuery.menuName.toLowerCase())
      
      // 菜单类型筛选
      const typeMatch = !appliedQuery.menuType || menu.menuType === appliedQuery.menuType
      
      // 状态筛选
      const statusMatch = appliedQuery.status === undefined || menu.status === appliedQuery.status
      
      const matched = nameMatch && typeMatch && statusMatch
      
      // 递归处理子菜单
      if (menu.children) {
        const filteredChildren = filterMenu(menu.children)
        
        if (matched || filteredChildren.length > 0) {
          return {
            ...menu,
            children: filteredChildren
          }
        }
      }
      
      return matched
    }).map(menu => {
      const children = menu.children || []
      return {
        ...menu,
        children: filterMenu(children)
      }
    })
  }
  
  return filterMenu(menuList.value)
})

// 方法 - 直接使用后端返回的数据，不做转换
const getList = async () => {
  loading.value = true
  try {
    const response = await menuApi.getMenuTree()
    // 直接使用后端返回的数据，不做任何字段转换
    menuList.value = response.data || []
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    ElMessage.error('获取菜单列表失败')
  } finally {
    loading.value = false
  }
}

const getMenuTypeText = (type: string) => {
  const norm = (type || '').toUpperCase()
  const map: Record<string, string> = {
    'DIR': '目录', 'M': '目录',
    'MENU': '菜单', 'C': '菜单',
    'BUTTON': '按钮', 'F': '按钮'
  }
  return map[norm] || norm
}

const handleQuery = () => {
  // 点击搜索时，将用户输入的条件应用到实际查询
  appliedQuery.menuName = queryParams.menuName
  appliedQuery.menuType = queryParams.menuType
  appliedQuery.status = queryParams.status
}

const resetQuery = () => {
  // 清空表单输入
  queryParams.menuName = ''
  queryParams.menuType = ''
  queryParams.status = undefined
  
  // 清空应用的查询条件
  appliedQuery.menuName = ''
  appliedQuery.menuType = ''
  appliedQuery.status = undefined
}

const toggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
}

const handleAdd = () => {
  isEdit.value = false
  
  // 重置表单数据 - 使用后端字段名
  Object.assign(formData, {
    id: undefined,
    name: '',
    title: '',
    parentId: null,
    path: '',
    component: '',
    icon: '',
    menuType: 'MENU',
    permission: '',
    orderNo: 0,
    status: 1,
    visible: true,
    isFrame: false,
    isCache: true
  })
  
  formVisible.value = true
  
  // 清除表单校验状态
  nextTick(() => {
    if (menuFormRef.value) {
      menuFormRef.value.clearValidate()
    }
  })
}

const handleAddChild = (row: MenuDTO) => {
  isEdit.value = false
  
  // 重置表单数据，并设置父菜单 - 使用后端字段名
  Object.assign(formData, {
    id: undefined,
    name: '',
    title: '',
    parentId: (row as any).id || '',
    path: '',
    component: '',
    icon: '',
    menuType: 'MENU',
    permission: '',
    orderNo: 0,
    status: 1,
    visible: true,
    isFrame: false,
    isCache: true
  })
  
  formVisible.value = true
  
  // 清除表单校验状态
  nextTick(() => {
    if (menuFormRef.value) {
      menuFormRef.value.clearValidate()
    }
  })
}

const handleEdit = (row: MenuDTO) => {
  formVisible.value = true
  isEdit.value = true
  
  // 先填充表单数据 - 直接使用后端字段名
  const rowData = row as any
  Object.assign(formData, {
    id: rowData.id,
    name: rowData.name || '',
    title: row.title || '',
    parentId: rowData.parentId || null,
    path: rowData.path || '',
    component: rowData.component || '',
    icon: rowData.icon || '',
    menuType: row.menuType || 'MENU',
    permission: rowData.permission || '',
    orderNo: row.orderNo || 0,
    status: row.status ?? 1,
    visible: row.visible ?? true,
    isFrame: row.isFrame ?? false,
    isCache: row.isCache ?? true
  })
  
  // 确保在下一个tick重置表单校验状态，但不清空已填充的值
  nextTick(() => {
    if (menuFormRef.value) {
      menuFormRef.value.clearValidate()
    }
  })
  
  // 调试信息（开发环境）
  if (import.meta.env.MODE === 'development') {
    console.log('编辑菜单 - 原始数据:', {
      id: rowData.id,
      parentId: rowData.parentId,
      title: row.title
    })
    console.log('编辑菜单 - 表单数据:', {
      id: formData.id,
      parentId: formData.parentId,
      title: formData.title
    })
  }
}

const handleDelete = async (row: MenuDTO) => {
  try {
    // 检查是否有子菜单
    const hasChildren = row.children && row.children.length > 0
    
    if (hasChildren) {
      ElMessage.warning('该菜单包含子菜单，请先删除子菜单')
      return
    }
    
    const rowData = row as any
    await ElMessageBox.confirm(
      `确定要删除菜单"${row.title || rowData.name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await menuApi.deleteMenu(rowData.id!)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 表单提交 - 直接使用后端字段名
const handleSubmit = async () => {
  try {
    if (!menuFormRef.value) return
    await menuFormRef.value.validate()

    loading.value = true

    // 准备提交数据 - 直接使用后端字段名
    const submitData: any = {
      name: formData.name,
      title: formData.title,
      parentId: formData.parentId || null,
      path: formData.path,
      component: formData.component,
      icon: formData.icon,
      menuType: formData.menuType,
      permission: formData.permission,
      orderNo: formData.orderNo,
      status: formData.status,
      visible: formData.visible,
      isFrame: formData.isFrame,
      isCache: formData.isCache
    }

    if (isEdit.value) {
      // 编辑菜单
      await menuApi.updateMenu(formData.id!, submitData)
      ElMessage.success('菜单更新成功')
    } else {
      // 新增菜单
      await menuApi.createMenu(submitData)
      ElMessage.success('菜单创建成功')
    }

    formVisible.value = false
    getList()
  } catch (error: any) {
    console.error('保存菜单失败:', error)
    if (error?.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('保存失败')
    }
  } finally {
    loading.value = false
  }
}

// 表单取消
const handleCancel = () => {
  formVisible.value = false
  if (menuFormRef.value) {
    menuFormRef.value.resetFields()
  }
}

// 获取图标组件
const getIconComponent = (iconName: string | undefined) => {
  if (!iconName) return null
  return ElementPlusIcons[iconName as keyof typeof ElementPlusIcons] || null
}

// 生命周期
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
// 可以在这里添加自定义样式
</style>
